# -*- coding: utf-8 -*-
# File : configure_service.py
# Author: taoyahui
# Date : 2021/7/11
from fabric import Connection
import json
from utils import common_util, mysql_util
import results
import os
import time
import configparser
from utils.log_util import logger

cf = configparser.ConfigParser()
cf.read(os.path.join(common_util.get_root_dir(),"config.ini"))

secs = cf.sections()
ip = cf.get("target-conf", "host")
port = cf.get("target-conf", "port")
username = cf.get("target-conf", "username")
password = cf.get("target-conf", "password")


# 获取系统的信息(cpu、ram、disk等等)
def get_system_configure():
    logger.info("get_system_configure -> 开始获取系统设置信息")
    c = Connection(f"{username}@{ip}", connect_kwargs={'password': password})

    try:
        cpu = cpu_usage(c)
        memory = c.run('free -m | awk \'NR==2{printf "%s/%s %.2f", $3,$2,$3*100/$2 }\'')
        disk_space = c.run(
            'lsblk |egrep \'^(v|s)d[a-z]\' |awk \'{print $4}\'|sed \'s/[a-Z]//\'|awk \'{disk[$1]++} END {for(i in '
            'disk){print i}}\' |awk \'{sum +=$1};END{print sum}\'')
        disk_remainder = c.run(
            'df -k | grep -v "tmpfs" | egrep -A 1 "mapper|sd" | awk \'NF>1{print $(NF-4)}\' | awk -v used=0 \'{'
            'used+=$1}END{printf "%.2f\\n",used/1048576}\'')
        interface = c.run('ip route show | sed -e \'s/^.*dev \([^ ]*\).*$/\\1/\' | head -n 1')
        speed = monitor_speed()
        d = {
                'cpu_used': cpu,
                'memory_used': memory.stdout.split(' ')[1],
                'rom_used': disk_space.stdout,
                'rom_remaind': disk_remainder.stdout.strip(),
                'net_card': interface.stdout.strip(),
                'tx_in_speed': speed['in'],
                'tx_out_speed': speed['out']
            }

        # res = common_util.gen_modify_res(200, d)
        # return res

        insert_sql = mysql_util.generate_insert_sql(d, 'sys_conf')
        mysql_util.exec_sql_params(insert_sql, tuple(d.values()))
        logger.info("get_system_configure ->完成获取系统设置信息")
        # delete_sql = "Delete sys_conf where "

    except Exception as e:
        logger.error(f"Get Configure Error IP : {ip}, Error  : {e}")
    finally:
        c.close()
    # return results.system_configure_error


def get_net_speed(net_card):
    logger = common_util.get_logger('get_system_configure')
    c = Connection(f"{username}@{ip}", connect_kwargs={'password': password})
    speed1 = float(c.run(f"cat /sys/class/net/{net_card}/statistics/rx_bytes").stdout.strip())
    time.sleep(1)
    speed2 = float(c.run(f"cat /sys/class/net/{net_card}/statistics/rx_bytes").stdout.strip())

    current_speed = round((speed2 - speed1) / 1024.0,2)
    # print(current_speed)
    res = {
        'code': 200,
        'data': current_speed
    }
    return res


def monitor_speed():
    c = Connection(f"{username}@{ip}", connect_kwargs={'password': password})
    res = c.run("cat /proc/net/dev")
    # print(res.stdout)
    print("*" * 50)
    print("*" * 50)
    network_line = res.stdout.split('\n')
    this_downstream = 0
    this_upstream = 0
    for network in network_line[2:-1]:
        net_res = network.split()
        netcard_name = net_res[0][:-1]
        this_downstream += float(net_res[1])
        this_upstream += float(net_res[9])

    time.sleep(1)
    res = c.run("cat /proc/net/dev")
    network_line = res.stdout.split('\n')
    that_downstream = 0
    that_upstream = 0
    for network in network_line[2:-1]:
        net_res = network.split()
        netcard_name = net_res[0][:-1]
        that_downstream += float(net_res[1])
        that_upstream += float(net_res[9])

    downstream = (that_downstream - this_downstream) /1024
    upstream = (that_upstream - that_upstream) /1024
    data = {
        'in': f"{downstream}",
        'out': f"{upstream}"
    }
    return data


def cpu_usage(c):
    res = c.run("sar -u 1 1")
    res_list = res.stdout.split("\n")
    avg_res = res_list[-2].split()
    print(avg_res)
    cpu_usage = 100 - float(avg_res[-1])
    return round(cpu_usage,2)


def memory_usage(c):
    res = c.run('free')
    print(res.stdout)
    target_str = ''
    for line in res.stdout.split('\n'):
        if line.startswith("Mem"):
            target_str = line

    pass


def remote_source_configure():
    """
    生成远程源的配置文件
    :return:
    """
    root_dir = common_util.get_root_dir()
    c = Connection(f"{username}@{ip}", connect_kwargs={'password': password})
    c.run('mkdir -p /root/source_dir')
    c.put(os.path.join(root_dir, 'scripts', 'ClientFtpConf.sh'), '/root/source_dir')
    c.put(os.path.join(root_dir, 'scripts', 'ftp.repo.tem'), '/root/source_dir')
    with c.cd('/root/source_dir'):
        c.run('bash ClientFtpConf.sh')
    c.get('/root/source_dir/ftp.repo', os.path.join(root_dir, 'scripts', 'ftp.repo'))


if __name__ == '__main__':
    # print(get_system_configure('192.168.50.199', 'root', 'ccit2389'))
    # monitor_speed()
    remote_source_configure()